<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\common\model\TemplateModel;
use think\facade\Db;
use think\facade\Session;

class Template extends Common
{
    public function getList()
    {
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $keyword = input('keyword');

        $map = [];
        if(!empty($keyword)){
            $map[] = ['title','like','%'.$keyword.'%'];
        }
        $list = TemplateModel::pageList($map);
        return json(['code'=>0,'msg'=>'success','data'=>$list]);
    }

    public function add(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $data = $this->request->param('data');
        if(!empty($data['id'])){
            TemplateModel::update($data);
        }else{
            unset($data['id']);
            $data['admin_id'] = session('admin_id');
            TemplateModel::create($data);
        }
        return json(['code'=>0,'msg'=>'操作成功']);
    }
    
    // 管理
    public function editShu() {
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        

        $userList = Db::name('template')->order('create_time DESC')->select();
        if ($this->request->isPost()) {
            $id = input('post.id');
            $action = input('post.action');
            $status = input('post.status');
            $value = input('post.value');
            if($value == 'true'){
                $value = '1';
            }elseif($value == 'false'){
                $value = '0';
                
            }
            // 更新信息
            Db::name('template')->where('id', $id)->update([$status => $value]);    //更新模板
            Db::name('template')->where('id','<>',$id)->where('status', '1')->update([$status => 0]);     //修改其他模板
            $userList = Db::name('template')->where('status','1')->find();
            $title = $userList['title'] ? $userList['title'] :'/default';     //查询为空时输出默认模板
            $url = $userList['url'] ? $userList['url'] :'/template/default'; 
	        $template = Db::name('setting')->where('name','default')->update(['value' => $title]);
	        $template = Db::name('setting')->where('name','default_url')->update(['value' => $url]);
	        
            return json(['code'=>0,'data'=>$title,'data1'=>$url,'msg'=>'系统仅允许有且只有一个模板，已取消其他默认模板']);
            
        }
        $this->getSide();
        return $this->fetch();
    }

    public function del(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $id = $this->request->param('ids');
        $Delinfo = \app\common\model\TemplateModel::where('id',$id)->where('status', '1')->find();
        if($Delinfo){
            return json(['code'=>1,'msg'=>'默认模板无法删除，请设置其他模板后再次尝试']);
        }else{
            $Delsinfo = \app\common\model\TemplateModel::where('id',$id)->where('status', '0')->find();
            $Dinfo = $Delsinfo['title'];    //获取文件名称
            $dir = str_replace('\\', '/', './template/' . $Dinfo.'/');  // 获取模板绝对地址
            del_dir($dir);      //删除模板文件夹
            if(del_dir(runtime_path())){
                TemplateModel::destroy($id);    //删除数据库记录
                return json(['code'=>0,'msg'=>'删除成功']);
            }else{
                return json(['code'=>1,'msg'=>'删除失败']);
            }
        }
    }

    public function uploadTem(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $file = request()->file('file');

        try {
            // 验证文件格式
            validate(['file' => ['fileExt' => 'zip', 'fileMime' => 'application/zip']])->check(['file' => $file]);
            // 移动到框架应用根目录/public/storage/template 目录下
            $info =  \think\facade\Filesystem::disk('public')->putFile( 'template', $file,'uniqid');
            
            // 拼接上传后的文件绝对路径
            $uploadPath = str_replace('\\', '/', './storage/' . $info);
            // 定义解压路径
            $unzipPath  = './template/';
            $titles     = $file->getOriginalName(); //获取原始文件名
            $alltag     = explode('.zip',$titles);    //截取文件名 分开输出
            $urls       = 'https://'.$_SERVER['HTTP_HOST'].'/template/'.$alltag[0];     //输出解压域名
            // 实例化对象
            $zip = new \ZipArchive();
            //打开zip文档，如果打开失败返回提示信息
            if ($zip->open($uploadPath, \ZipArchive::CREATE) !== TRUE) {
                die ("Could not open archive");
            } else {
                //将压缩文件解压到指定的目录下
                $zip->extractTo($unzipPath);
                //关闭zip文档
                $zip->close();
                //解压后删除压缩包
                unlink($uploadPath);
                $data['code'] = 0;
                $data['msg'] = '上传成功';
                $data['url'] = $urls;
	            $data['title'] = $alltag[0];
            }
 
        } catch (ValidateException $e) {
            $this->error($e->getError());
            $data['code'] = 1;
            $data['msg'] = '上传失败';
            $data['info'] = $e->getError();
        }
        return json(['data'=>$data]);
    }
    

}
